// pages/sales/my_mall/re_goods_list.js
var cf = require("../../../config.js");
var util = require("../../../utils/util.js");
var cusmallToken = wx.getStorageSync('cusmallToken');
var baseHandle = require("../../template/baseHandle.js");
var app = getApp();
var vTimer = null;
Page(Object.assign({}, baseHandle, {

  /**
   * 页面的初始数据
   */
  data: {
    extConfig: wx.getExtConfigSync ? wx.getExtConfigSync() : {},
    app: app,
    employeeMsg: "",
    staticResPath: cf.config.staticResPath,
    userImagePath: cf.config.userImagePath,
    recorderManager: null,
    innerAudioContext:null,
    playing: false,
    recordStatus: 0, //0 等待录音 1 录音中 2 录音结束 3 播放临时录音
    tempSound: null,
    maxSeconds: 50,
    list: [
    ],
    isLoading: false,
    pageSize: 10,
    curPage: 1,
    isBottom: false,
    showVoiceModal: false,
    soundTime: "00",
    vTimer: null,
    curIdx:-1,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    wx.hideShareMenu();
    var ctx = this;
    var recorderManager = wx.getRecorderManager();
    var innerAudioContext = wx.createInnerAudioContext();
    ctx.setData({
      recorderManager: recorderManager,
      innerAudioContext: innerAudioContext,
    });
    recorderManager.onStart(ctx.soundRecordingCb);
    recorderManager.onStop(ctx.soundRecordedEndCb);

    app.getUserInfo(ctx, options, function(userInfo, res) {
      cusmallToken = wx.getStorageSync('cusmallToken');
      ctx.setData({
        employee: wx.getStorageSync('employee')
      });
      ctx.findGoodsList();
    });
  },
  closeVoice() {
    var ctx = this;
    ctx.resetSound();
    ctx.setData({
      showVoiceModal: false,
    });
  },
  playSound(e) {
    var ctx = this;
    var idx = e.currentTarget.dataset.idx;
    if (ctx.data.playing){
      return;
    }
    ctx.setData({
      playing: true,
      ["list[" + idx +"].playing"]:true
    });
    ctx.data.innerAudioContext.src = ctx.data.list[idx].voiceRecommended;
    var duration = ctx.data.innerAudioContext.duration;
    
    console.log(ctx.data.innerAudioContext.duration);
    ctx.data.innerAudioContext.onEnded(function(){
      console.log(111);
      ctx.setData({
        playing: false,
        ["list[" + idx + "].playing"]: false
      });
    });
    ctx.data.innerAudioContext.play();
  },
  addSound(e) {
    var ctx = this;
    ctx.setData({
      curIdx: e.currentTarget.dataset.idx
    })
    ctx.setData({
      showVoiceModal: true,
    });
    // ctx.resetSound();
  },
  /**
   * 录音开始
   */
  soundRecording() {
    var ctx = this;
    ctx.data.recorderManager.start();
  },
  soundRecordingCb() {
    console.log("started soundRecording");
    var ctx = this;
    ctx.setData({
      recordStatus: 1,
      recordStartTime: Date.now(),
    });
    vTimer = setInterval(function() {
      var soundTime = parseInt(ctx.data.soundTime)
      if (ctx.data.maxSeconds <= ctx.data.soundTime) {// 超过最大时间停止录音
        ctx.soundRecorded();
        return;
      }
      soundTime++;
      soundTime = soundTime < 10 ? "0" + soundTime : soundTime; //加前置0
      ctx.setData({
        soundTime: soundTime
      });
    }, 1000);
  },
  /**
   * 录音结束
   */
  soundRecorded() {
    var ctx = this;
    ctx.setData({
      recordEndTime: Date.now(),
    });
    ctx.data.recorderManager.stop();
  },
  soundRecordedEndCb(res) {
    var ctx = this;
    clearInterval(vTimer);
    const tempFilePath = res.tempFilePath;
    console.log(tempFilePath);
    ctx.setData({
      recordStatus: 2,
      tempSound: tempFilePath
    });
    console.log("end soundRecorded");
    //ctx.data.recordStartTime 只有长按才会 赋值，如果没有值说明并没有长按，如果录音少于1秒也是不允许的
    if (!ctx.data.recordStartTime || (Date.now()  - ctx.data.recordStartTime) < 1000) {
      ctx.resetSound();
    }
    ctx.setData({
      recordStartTime: null
    });
  },
  playTemSound() { //播放录制的声音
    var ctx = this;
    ctx.data.innerAudioContext.src = ctx.data.tempSound;
    ctx.data.innerAudioContext.play();
    var time = parseInt(ctx.data.soundTime) * 1000;
    // var timer = setTimeout(function() {
    //   ctx.setData({
    //     recordStatus: 2
    //   });
    // }, time);
    ctx.data.innerAudioContext.onEnded(function () {
      ctx.setData({
        recordStatus: 2
      });
    });

    ctx.setData({
      recordStatus: 3,
    });
  },
  resetSound() { //重置声音
    var ctx = this;
    clearInterval(vTimer);
    ctx.data.innerAudioContext.stop();
    ctx.setData({
      recordStatus: 0,
      tempSound: null,
      soundTime: "00"
    });
  },
  saveSound() {
    var ctx = this;
    ctx.uploadVoiceRecommended();
  },
  delRecorded(e) {
    var ctx = this;
    wx.showModal({
      title: '提示',
      content: '您确定要删除语音推荐吗？',
      success(res) {
        if (res.confirm) {
          console.log("suc")
          ctx.updateGoods(e);
        }
      }
    });
  },

  findGoodsList() {
    var ctx = this;
    if (ctx.data.isLoading || ctx.data.isBottom) {
      return;
    }
    ctx.setData({
      isLoading: true
    });
    wx.request({
      url: cf.config.pageDomain + "/applet/mobile/visitcard/goodsNew/findGoodsList",
      data: {
        cusmallToken: cusmallToken,
        eid: ctx.data.employee.id,
        start: (ctx.data.curPage - 1) * ctx.data.pageSize,
        limit: ctx.data.pageSize
      },
      header: {
        'content-type': 'application/json'
      },
      success: function(res) {
        var data = res.data;
        if (data && 0 === data.ret) {
          var list = data.model.result;
          for (let item of list) {
            item.pubTime = util.formatTime(new Date(item.createTime));

          }
          ctx.setData({
            list: ctx.data.list.concat(list),
          });
          if (data.model.total == ctx.data.list.length) {
            ctx.setData({
              isBottom: true
            });
          }
        } else {
          wx.showToast({
            title: data.msg,
          })
        }
      },
      fail() {

      },
      complete() {
        ctx.setData({
          isLoading: false
        });
      }
    });
  },
  //
  uploadVoiceRecommended() {
    var ctx = this;
    if (!ctx.data.tempSound) {
      wx.showToast({
        title: "声音文件为空",
        icon: "none"
      });
      return;
    }
    wx.showToast({
      icon: "loading",
      title: "正在上传"
    });
    var goodsId = ctx.data.list[ctx.data.curIdx].id;
    console.log(ctx.data.soundTime + "+++++-------")
    wx.uploadFile({
      url: cf.config.pageDomain + '/applet/mobile/visitcard/goodsNew/uploadVoiceRecommended?cusmallToken=' + cusmallToken,
      filePath: ctx.data.tempSound,
      name: 'voiceFile',
      header: {
        "Content-Type": "multipart/form-data"
      },
      formData: {
        //和服务器约定的token, 一般也可以放在header中
        goodsId: goodsId,
        eid: ctx.data.employee.id,
        voiceTime: ctx.data.soundTime
      },
      success: function(res) {
        wx.hideToast();
        console.log(res)
        var data = JSON.parse(res.data);
        if (data && 0 === data.ret){
          wx.showToast({
            title: "上传成功",
            icon: "none"
          });
          ctx.closeVoice();
          var item = ctx.data.list[ctx.data.curIdx];
          item.voiceRecommended = data.model.voiceUrl;
          ctx.setData({
            ["list[" + ctx.data.curIdx + "]"]: item
          })
        }else{
          wx.showToast({
            title: data.msg,
            icon: "none"
          });
        }

      },
      fail: function(e) {
        console.log(e);
        wx.hideToast();
        wx.showToast({
          title: "上传失败",
          icon:"none"
        });
        console.log(e)
      },
      complete: function() {
      }
    })
  },
  //
  updateGoods(e){
    var ctx = this;
    var idx = e.currentTarget.dataset.idx;
    var op = e.currentTarget.dataset.op;
    var reqUrl = "/applet/mobile/visitcard/goodsNew/updateRecommendedGoods";//默认推荐商品接口
    var submitData = {
      cusmallToken: cusmallToken,
      goodsId: ctx.data.list[idx].id,
      eid: ctx.data.employee.id
    }
    if("isRe" == op){
      submitData.isRecommended = false;
    } else if ("isNotRe" == op){
      submitData.isRecommended = true;
    } else if("delVoice" == op){
      reqUrl = "/applet/mobile/visitcard/goodsNew/deleteVoiceRecommended";//声音推荐接口
    }
    ctx.updateGoodsHandle(submitData, op, idx, reqUrl)
  },
  updateGoodsHandle(submitData, op, idx, reqUrl){
    var ctx = this;
    wx.request({
      url: cf.config.pageDomain + reqUrl,
      data: submitData,
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        var data = res.data;
        if (data && 0 === data.ret) {
          var txt = "";
          if ("isRe" == op) {
            txt = "已取消推荐";
            ctx.setData({
              ["list[" + idx + "].isRecommended"] : submitData.isRecommended
            });
          } else if ("isNotRe" == op) {
            ctx.setData({
              ["list[" + idx + "].isRecommended"]: submitData.isRecommended
            });
            txt = "推荐成功";
          } else if ("delVoice" == op) {
            ctx.setData({
              ["list[" + idx + "].voiceRecommended"]: false
            });
            txt = "删除成功";
          }
          wx.showToast({
            title: txt,
            icon:"none"
          });
        } else {
          wx.showToast({
            title: data.msg,
          })
        }
      },
      fail() {

      },
      complete() {
      }
    });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {
    var ctx = this;
    ctx.setData({
      list: [],
      isLoading: false,
      curPage: 1,
      isBottom: false,
    });
    ctx.findGoodsList();
    wx.stopPullDownRefresh();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {
    var ctx = this;
    if (!ctx.data.isLoading) {
      ctx.setData({
        curPage: ctx.data.curPage + 1
      });
      ctx.findGoodsList();
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
}))